'use client';

import { Controller, useForm } from 'react-hook-form';
import { Button, DialogActions, DialogContent, MenuItem, Stack, TextField } from '@mui/material';

interface QuestionFormProps {
  initialValues?: any;
  onFinish: (values: any) => void;
  onCancel: () => void;
  submitText?: string;
}

export default function QuestionForm({ initialValues, onFinish, onCancel, submitText = '确认' }: QuestionFormProps) {
  const { control, handleSubmit, watch, reset } = useForm({
    defaultValues: {
      type: initialValues?.type || 'CHOICE',
      subject: initialValues?.subject || '',
      content: initialValues?.content || '',
      options: initialValues?.type === 'CHOICE' ? 
        (Array.isArray(initialValues?.options) ? initialValues.options : 
        (typeof initialValues?.options === 'string' ? initialValues.options.split('\n').filter(Boolean) : [])) : [],
      answer: initialValues?.answer || '',
      explanation: initialValues?.explanation || '',
      score: initialValues?.score || 1.0
    }
  });

  return (
    <form onSubmit={handleSubmit(onFinish)}>
      <DialogContent>
        <Stack spacing={3}>
          <Controller
            name="subject"
            control={control}
            rules={{ required: '请选择科目' }}
            render={({ field, fieldState: { error } }) => (
              <TextField
                {...field}
                select
                label="科目"
                error={!!error}
                helperText={error?.message}
                fullWidth
              >
                <MenuItem value="语文">语文</MenuItem>
                <MenuItem value="数学">数学</MenuItem>
                <MenuItem value="英语">英语</MenuItem>
                <MenuItem value="物理">物理</MenuItem>
                <MenuItem value="化学">化学</MenuItem>
                <MenuItem value="生物">生物</MenuItem>
                <MenuItem value="历史">历史</MenuItem>
                <MenuItem value="地理">地理</MenuItem>
                <MenuItem value="政治">政治</MenuItem>
              </TextField>
            )}
          />

          <Controller
            name="type"
            control={control}
            rules={{ required: '请选择题目类型' }}
            render={({ field, fieldState: { error } }) => (
              <TextField
                {...field}
                select
                label="题目类型"
                error={!!error}
                helperText={error?.message}
                fullWidth
              >
                <MenuItem value="CHOICE">选择题</MenuItem>
                <MenuItem value="TRUE_FALSE">判断题</MenuItem>
                <MenuItem value="FILL_BLANK">填空题</MenuItem>
                <MenuItem value="SHORT_ANSWER">简答题</MenuItem>
              </TextField>
            )}
          />

          <Controller
            name="content"
            control={control}
            rules={{ required: '请输入题目内容' }}
            render={({ field, fieldState: { error } }) => (
              <TextField
                {...field}
                label="题目内容"
                multiline
                rows={4}
                error={!!error}
                helperText={error?.message}
                fullWidth
              />
            )}
          />

          {watch('type') === 'CHOICE' && (
            <Controller
              name="options"
              control={control}
              rules={{
                required: '请输入选项',
                validate: (value) => {
                  const options = Array.isArray(value) ? value : value.split('\n').filter(Boolean);
                  if (options.length < 2) return '至少需要两个选项';
                  if (options.length > 4) return '最多只能有四个选项';
                  return true;
                }
              }}
              render={({ field, fieldState: { error } }) => (
                <TextField
                  {...field}
                  label="选项"
                  multiline
                  rows={4}
                  placeholder="每行输入一个选项（2-4个选项）"
                  error={!!error}
                  helperText={error?.message}
                  fullWidth
                  value={Array.isArray(field.value) ? field.value.join('\n') : field.value || ''}
                  onChange={(e) => {
                    const options = e.target.value
                      .split('\n')
                      .map(opt => opt.trim())
                      .filter(opt => opt.length > 0);
                    field.onChange(options);
                  }}
                  onKeyDown={(e) => {
                    if (e.key === 'Enter' && !e.shiftKey) {
                      e.preventDefault();
                      const currentValue = field.value || '';
                      const options = Array.isArray(currentValue) ? currentValue : currentValue.split('\n').filter(Boolean);
                      if (options.length < 4) {
                        const newValue = Array.isArray(currentValue) ? [...currentValue, ''] : currentValue + '\n';
                        field.onChange(newValue);
                      }
                    }
                  }}
                />
              )}
            />
          )}

          {watch('type') === 'CHOICE' && Array.isArray(watch('options')) && watch('options').length > 0 ? (
            <Controller
              name="answer"
              control={control}
              rules={{ required: '请选择答案' }}
              render={({ field, fieldState: { error } }) => (
                <TextField
                  {...field}
                  select
                  label="答案"
                  error={!!error}
                  helperText={error?.message}
                  fullWidth
                >
                  {watch('options') && typeof watch('options') === 'string' 
                    ? watch('options')
                        .split('\n')
                        .filter(Boolean)
                        .map((option, index) => (
                          <MenuItem key={index} value={String.fromCharCode(65 + index)}>
                            {String.fromCharCode(65 + index)}. {option}
                          </MenuItem>
                        ))
                    : Array.isArray(watch('options'))
                        ? watch('options').map((option, index) => (
                            <MenuItem key={index} value={String.fromCharCode(65 + index)}>
                              {String.fromCharCode(65 + index)}. {option}
                            </MenuItem>
                          ))
                        : null
                  }
                </TextField>
              )}
            />
          ) : watch('type') === 'TRUE_FALSE' ? (
            <Controller
              name="answer"
              control={control}
              rules={{ required: '请选择答案' }}
              render={({ field, fieldState: { error } }) => (
                <TextField
                  {...field}
                  select
                  label="答案"
                  error={!!error}
                  helperText={error?.message}
                  fullWidth
                >
                  <MenuItem value="true">正确</MenuItem>
                  <MenuItem value="false">错误</MenuItem>
                </TextField>
              )}
            />
          ) : (
            <Controller
              name="answer"
              control={control}
              rules={{ required: '请输入答案' }}
              render={({ field, fieldState: { error } }) => (
                <TextField
                  {...field}
                  label="答案"
                  multiline={watch('type') === 'SHORT_ANSWER'}
                  rows={watch('type') === 'SHORT_ANSWER' ? 4 : 1}
                  error={!!error}
                  helperText={error?.message}
                  fullWidth
                />
              )}
            />
          )}

          <Controller
            name="score"
            control={control}
            rules={{ required: '请输入分值' }}
            render={({ field, fieldState: { error } }) => (
              <TextField
                {...field}
                label="分值"
                type="number"
                inputProps={{ min: 0.5, step: 0.5 }}
                error={!!error}
                helperText={error?.message}
                fullWidth
              />
            )}
          />

          <Controller
            name="explanation"
            control={control}
            rules={{ required: '请输入解析' }}
            render={({ field, fieldState: { error } }) => (
              <TextField
                {...field}
                label="解析"
                multiline
                rows={4}
                error={!!error}
                helperText={error?.message}
                fullWidth
              />
            )}
          />
        </Stack>
      </DialogContent>
      <DialogActions>
        <Button onClick={onCancel}>取消</Button>
        <Button type="submit" variant="contained">{submitText}</Button>
      </DialogActions>
    </form>
  );
}